<template>
  <div class="app-container">
    <el-row>
      <el-col :span="4" :xs="24">
        <el-tree :data="orgTreeData" :props="defaultProps" @node-click="handleNodeClick" />
      </el-col>

      <el-col :span="20" :xs="24">
        <div class="filter-container">
          <el-form ref="listQuery" :rules="rules" :model="listQuery" :inline="true" label-position="left" label-width="80px">
            <el-form-item label="账号">
              <el-input v-model="listQuery.account" placeholder="账号名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
            </el-form-item>
            <el-form-item label="手机号码">
              <el-input v-model="listQuery.phone" placeholder="账号编码" class="filter-item" @keyup.enter.native="handleFilter" />
            </el-form-item>
            <el-form-item>
              <el-button-group>
                <el-button v-waves type="primary" class="filter-item" icon="el-icon-search" @click="handleFilter">查询</el-button>
                <el-button class="filter-item" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
              </el-button-group>
            </el-form-item>
            <el-form-item>
              <el-button class="filter-item" type="primary" icon="el-icon-plus" @click="handleCreate">
                新增
              </el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-table
          :key="tableKey"
          v-loading="listLoading"
          :data="list"
          border
          fit
          highlight-current-row
          style="width: 100%;"
          size="small"
        >
          <el-table-column align="center" label="序号" width="55" type="index" fixed />
          <el-table-column prop="account" align="center" label="账号" width="120" fixed />
          <el-table-column prop="nickName" align="center" label="昵称" width="120" />
          <el-table-column align="center" label="头像" width="80">
            <template slot-scope="scope">
              <el-avatar :size="30" :src="scope.row.avatar">
                {{ scope.row.nickName.slice(0, 1) }}
              </el-avatar>
            </template>
          </el-table-column>
          <el-table-column prop="realName" align="center" label="姓名" width="120" />
          <el-table-column label="出生日期" width="120" align="center">
            <template slot-scope="{row}">
              <span>{{ row.birthday | parseTime('{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="性别" width="70">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.sex === 1" type="success"> 男 </el-tag>
              <el-tag v-else type="danger"> 女 </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="phone" align="center" label="手机号码" width="120" />
          <el-table-column prop="orderNo" align="center" label="排序" width="100" />
          <el-table-column align="center" label="状态" class-name="status-col" width="70">
            <template slot-scope="{row}">
              <el-tag v-if="row.status === 1" type="success">启用</el-tag>
              <el-tag v-else type="danger">禁用</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="修改时间" width="160" align="center" />
          <el-table-column prop="remark" label="备注" header-align="center" />
          <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width" fixed="right">
            <template slot-scope="{row}">
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="handleUpdate(row)">
                编辑
              </el-button>
              <el-dropdown style="padding: 7px" @command="(command) => handleCommand(command, row)">
                <i class="el-icon-more" />
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item icon="el-icon-refresh" command="handleReset">重置密码</el-dropdown-item>
                  <el-dropdown-item icon="el-icon-delete" command="handleDelete">删除账号</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.pageSize" @pagination="getList" />

        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
          <el-tabs v-model="activeName" style="margin-top:-20px" @tab-click="handleTabClick">
            <el-tab-pane label="基本信息" name="jbxx">
              <el-form ref="jbxxForm" :rules="rules" :model="temp" label-position="right" label-width="90px">
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="账号名称" prop="account">
                      <el-input id="account" v-model="temp.account" placeholder="请输入账号名称" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="真实姓名" prop="realName">
                      <el-input id="realName" v-model="temp.realName" placeholder="请输入真实姓名" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="昵称" prop="nickName">
                      <el-input id="nickName" v-model="temp.nickName" placeholder="请输入昵称" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="手机号码" prop="phone">
                      <el-input id="phone" v-model="temp.phone" placeholder="请输入手机号码" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="出生日期" prop="birthday">
                      <el-date-picker id="birthday" v-model="temp.birthday" type="date" placeholder="请选择出生日期" style="width:100%" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="性别" prop="sex">
                      <el-radio-group id="sex" v-model="temp.sex">
                        <el-radio :label="1">男</el-radio>
                        <el-radio :label="2">女</el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="角色" prop="roleIdList">
                      <el-select id="roleIdList" v-model="temp.roleIdList" multiple clearable filterable placeholder="请选择角色" style="width:100%">
                        <el-option
                          v-for="item in roleData"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="排序" prop="orderNo">
                      <el-input-number id="orderNo" v-model="temp.orderNo" :min="1" :max="10" label="排序" style="width:100%" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-divider border-style="dashed" content-position="center">
                  <div style="color: #b1b3b8">机构组织</div>
                </el-divider>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="所属机构" prop="orgId">
                      <el-cascader
                        id="orgId"
                        v-model="temp.orgId"
                        :options="orgTreeData"
                        :props="{ checkStrictly: true, emitPath: false, value: 'id', label: 'name', expandTrigger: 'hover' }"
                        placeholder="请选择所属机构"
                        clearable
                        style="width:100%"
                      >
                        <template slot-scope="{ node, data }">
                          <span>{{ data.name }}</span>
                          <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
                        </template>
                      </el-cascader>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="职位" prop="posId">
                      <el-select id="posId" v-model="temp.posId" filterable placeholder="职位" style="width:100%">
                        <el-option
                          v-for="item in posData"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="工号" prop="jobNum">
                      <el-input id="jobNum" v-model="temp.jobNum" placeholder="请输入工号" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="入职日期" prop="joinDate">
                      <el-date-picker id="joinDate" v-model="temp.joinDate" type="date" placeholder="请选择入职日期" style="width:100%" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-divider border-style="dashed" content-position="center">
                  <div style="color: #b1b3b8">附属机构</div>
                </el-divider>
                <el-row>
                  <el-col :span="24">
                    <el-table
                      :data="temp.extOrgIdList"
                      border
                      highlight-current-row
                      style="width: 100%"
                    >
                      <el-table-column align="center" label="机构">
                        <template slot-scope="{row}">
                          <el-cascader
                            :id="`orgId${row.id}`"
                            v-model="row.orgId"
                            :options="orgTreeData"
                            :props="{ checkStrictly: true, emitPath: false, value: 'id', label: 'name', expandTrigger: 'hover' }"
                            placeholder="请选择机构"
                            clearable
                            style="width:100%"
                          >
                            <template slot-scope="{ node, data }">
                              <span>{{ data.name }}</span>
                              <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
                            </template>
                          </el-cascader>
                        </template>
                      </el-table-column>
                      <el-table-column align="center" label="职位">
                        <template slot-scope="{row}">
                          <el-select :id="`posId${row.id}`" v-model="row.posId" filterable placeholder="职位" style="width:100%">
                            <el-option
                              v-for="item in posData"
                              :key="item.id"
                              :label="item.name"
                              :value="item.id"
                            />
                          </el-select>
                        </template>
                      </el-table-column>
                      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
                        <template slot="header">
                          <el-button icon="el-icon-plus" type="primary" size="mini" plain @click="addExtOrgRow"> 新增 </el-button>
                        </template>
                        <template slot-scope="{row}">
                          <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteExtOrgRow(row)">
                            删除
                          </el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                  </el-col>
                </el-row>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="档案信息" name="daxx">
              <el-form ref="daxxForm" :rules="rules" :model="temp" label-position="right" label-width="90px">
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="证件类型" prop="cardType">
                      <el-select id="cardType" v-model="temp.cardType" filterable placeholder="证件类型" style="width:100%">
                        <el-option
                          v-for="item in cardTypeData"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="证件号码" prop="idCardNum">
                      <el-input id="idCardNum" v-model="temp.idCardNum" placeholder="请输入证件号码" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="民族" prop="nation">
                      <el-input id="nation" v-model="temp.nation" placeholder="请输入民族" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="邮箱" prop="email">
                      <el-input id="email" v-model="temp.email" placeholder="请输入邮箱" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="地址" prop="address">
                      <el-input id="address" v-model="temp.address" placeholder="请输入地址" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="毕业学校" prop="college">
                      <el-input id="college" v-model="temp.college" placeholder="请输入毕业学校" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="文化程度" prop="email">
                      <el-select id="cultureLevel" v-model="temp.cultureLevel" filterable placeholder="证件类型" style="width:100%">
                        <el-option
                          v-for="item in cultureLevelData"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="政治面貌" prop="politicalOutlook">
                      <el-input id="politicalOutlook" v-model="temp.politicalOutlook" placeholder="请输入政治面貌" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="办公电话" prop="officePhone">
                      <el-input id="officePhone" v-model="temp.officePhone" placeholder="请输入办公电话" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="紧急联系人" prop="emergencyContact">
                      <el-input id="emergencyContact" v-model="temp.emergencyContact" placeholder="请输入紧急联系人" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="联系人电话" prop="emergencyPhone">
                      <el-input id="emergencyPhone" v-model="temp.emergencyPhone" placeholder="请输入联系人电话" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="联系人地址" prop="emergencyAddress">
                      <el-input id="emergencyAddress" v-model="temp.emergencyAddress" placeholder="请输入联系人地址" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="备注">
                      <el-input v-model="temp.remark" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="请输入备注" />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </el-tab-pane>
          </el-tabs>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">
              取 消
            </el-button>
            <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
              确 定
            </el-button>
          </div>
        </el-dialog>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getUsers, addUser, deleteUser, updateUser, resetUser } from '@/api/user'
import { sysOrgList, ownExtOrgList } from '@/api/org'
import { getPosList } from '@/api/pos'
import { getRoleList, ownRoleList } from '@/api/role'

import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  name: 'SysUser',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        pageSize: 20,
        account: undefined,
        phone: undefined,
        orgId: undefined
      },
      orgTreeData: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      temp: {
        id: undefined,
        name: '',
        code: '',
        orderNo: 100,
        status: 1,
        roleIdList: [],
        extOrgIdList: []
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑账号',
        create: '添加账号'
      },
      rules: {
        account: [{ required: true, message: '账号名称不能为空', trigger: 'blur' }],
        realName: [{ required: true, message: '真实姓名不能为空', trigger: 'blur' }]
      },
      activeName: 'jbxx',
      roleData: [],
      posData: [],
      cardTypeData: [{ id: 0, name: '身份证' }, { id: 1, name: '护照' }, { id: 2, name: '出生证' }, { id: 3, name: '港澳台通行证' }, { id: 4, name: '外国人居留证' }],
      cultureLevelData: [{ id: 0, name: '其他' }, { id: 1, name: '小学' }, { id: 2, name: '初中' }, { id: 3, name: '普通高中' }, { id: 4, name: '技工学校' }, { id: 5, name: '职业教育' }, { id: 6, name: '职业高中' }, { id: 7, name: '中等专科' }, { id: 8, name: '大学专科' }, { id: 9, name: '大学本科' }, { id: 10, name: '硕士研究生' }, { id: 11, name: '博士研究生' }]
    }
  },
  created() {
    this.getList()
    this.getOrgs()
    this.getPoss()
    this.getRoles()
  },
  methods: {
    getList() {
      this.listLoading = true
      getUsers(this.listQuery).then(response => {
        this.listLoading = false
        this.list = response.result.items
        this.total = response.result.total
      })
    },
    async getOrgs() {
      const res = await sysOrgList()
      this.orgTreeData = res.result ?? []
    },
    async getPoss() {
      const res = await getPosList()
      this.posData = res.result ?? []
    },
    async getRoles() {
      const res = await getRoleList()
      this.roleData = res.result ?? []
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetQuery() {
      this.listQuery.name = ''
      this.listQuery.code = ''
      this.listQuery.page = 1
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        roleIdList: [],
        extOrgIdList: []
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['jbxxForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['jbxxForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          addUser(tempData).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '新增账号成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    async handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      const roleIds = await ownRoleList(row.id)
      this.temp.roleIdList = roleIds.result ?? []
      const extOrgs = await ownExtOrgList(row.id)
      this.temp.extOrgIdList = extOrgs.result ?? []
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['jbxxForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['jbxxForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateUser(tempData).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              message: '编辑账号成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleReset(row) {
      this.$confirm('确定重置密码吗?', '提示信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await resetUser(row.id)
          this.$message({
            type: 'success',
            message: '密码重置成功!'
          })
        })
        .catch(err => { console.error(err) })
    },
    handleDelete(row) {
      this.$confirm('确定删除账号吗?', '提示信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await deleteUser(row.id)
          this.getList()
          this.$message({
            type: 'success',
            message: '删除账号成功!'
          })
        })
        .catch(err => { console.error(err) })
    },
    handleNodeClick(row) {
      this.listQuery.orgId = row.id
      this.getList()
    },
    handleCommand(command, row) {
      switch (command) {
        case 'handleDelete':
          this.handleDelete(row)
          break
        case 'handleReset':
          this.handleReset(row)
          break
        default:
          break
      }
    },
    handleTabClick(tab, event) {
      this.activeName = tab.name
    },
    addExtOrgRow() {
      if (this.temp.extOrgIdList === undefined) { this.temp.extOrgIdList = [] }
      this.temp.extOrgIdList?.push({})
    },
    deleteExtOrgRow(row) {
      this.temp.extOrgIdList?.splice(row.id, 1)
    }
  }
}
</script>

<style scoped>
.el-form-item{
  margin-bottom: 10px;
}
.filter-container .el-form-item{
    margin-bottom: auto;
}
</style>
